<template>
  <div class="app-container">
    <div class="app-container-content systemuser">
      <!-- 操作区域 -->
      <div class="btn">
        <div class="left">
          <el-button type="primary" size="mini" icon="el-icon-plus" @click.native="handleAdd()">新增</el-button>
          <!-- <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="handleDel(selectList)"
          >批量删除</el-button> -->
        </div>
      </div>
      <div ref="tablebox" class="tablebox">
        <el-table
          :data="tableData"
          style="width: 100%"
          @select="handleSelectList"
          @sort-change="handleSortChange"
        >
          <!-- <el-table-column type="selection" width="55" /> -->
          <el-table-column prop="username" label="用户名" />
          <el-table-column label="角色">
            <template slot-scope="scope">{{ scope.row.roles.map(item=>item.name).join(',') }}</template>
          </el-table-column>
          <!-- <el-table-column prop="avatar" label="头像">
            <template slot-scope="scope">
              <img v-if="scope.row.avatar" :src="scope.row.avatar" width="45" height="45"/>
            </template>
          </el-table-column> -->
          <el-table-column prop="nickname" label="姓名" />
          <el-table-column prop="gender" label="性别">
            <template slot-scope="scope">
              {{ scope.row.gender == 1 ? '男' : (scope.row.gender == 2 ? '女' : '未知') }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="180px" align="center">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 1" size="small" type="success">正常</el-tag>
              <el-tag v-if="scope.row.status === 2" size="small" type="danger">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="240px" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="success" @click="handleAdd(scope.row)">编辑</el-button>

              <el-button v-if="scope.row.username !== 'admin'" size="mini" type="danger" @click="handleDel([scope.row.id])">删除</el-button>
              <el-button v-else disabled size="mini" type="danger" @click="handleDel([scope.row.id])">删除</el-button>

              <el-button v-if="scope.row.username !== 'admin'" size="mini" type="warning" @click="resetPassWord(scope.row.id)">重置密码</el-button>
              <el-button v-else disabled size="mini" type="warning" @click="resetPassWord(scope.row.id)">重置密码</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        background
        layout="total, prev, pager, next, sizes, jumper"
        :total="pageCondition.total"
        :page-sizes="[5, 10, 15, 30, 50, 100]"
        :page-size="pageCondition.size"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <!-- 新增谈出窗口 -->
      <el-dialog
        :title="handleType"
        :visible.sync="addDialogShow"
        width="30%"
        :before-close="handleClose"
        :close-on-click-modal="false"
      >
        <div v-if="addDialogShow" class="dialog-content">
          <el-form ref="from" :rules="rules" label-width="80px" :model="userForm">
            <el-form-item v-if="handleType=='新增'" prop="username" label="用户名">
              <el-input v-model="userForm.username" />
            </el-form-item>
            <el-form-item prop="nickname" label="姓名">
              <el-input v-model="userForm.nickname" />
            </el-form-item>
            <el-form-item prop="gender" label="性别">
              <el-radio-group v-model="userForm.gender">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item prop="status" label="状态">
              <el-select v-model="userForm.status" placeholder="用户状态">
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item prop="roles" label="角色">
              <el-select v-model="userForm.roles" multiple>
                <el-option
                  v-for="item in roleOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div slot="footer">
          <el-button type="primary" @click="onSubmit('from')">确认</el-button>
          <el-button @click="handleClose">取消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import roleApi from '@/api/system/role'
import userApi from '@/api/system/systemuser'
import { mapState } from 'vuex'

export default {
  filters: {},
  data() {
    var validateUsername = (rule, value, callback) => { // 验证用户名不为空且不为汉字
      if (!value) {
        return callback(new Error('用户名不能为空'))
      }
      if (/[\u4E00-\u9FA5]/g.test(value)) {
        return callback(new Error('用户名不能为汉字'))
      } else {
        callback()
      }
    }
    var validateRoles = (rule, value, callback) => {
      if (!value || value.length == 0) {
        return callback(new Error('角色不能为空'))
      } else {
        callback()
      }
    }
    return {
      rules: { // 校验方法
        username: [{ validator: validateUsername, trigger: 'blur', required: true }],
        status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
        roles: [{ validator: validateRoles, trigger: 'blur', required: true }]
      },
      addDialogShow: false, // 新增弹出框是否显示
      handleType: '新增',
      userForm: {},
      statusOptions: [
        {
          value: 1,
          label: '正常'
        },
        {
          value: 2,
          label: '禁用'
        }
      ],
      roleOptions: [],
      tableData: [], // 展现表格的数据
      pageCondition: {
        page: 1,
        size: 15,
        sort: '',
        total: 0
      }, // 分页条件
      selectList: [] // 多选列表的id
    }
  },
  created() {
    this.listPage()
    this.getRolesList()
  },
  computed: {
    ...mapState({
      roles: state => state.user.roles
    })
  },
  methods: {
    listPage: function() {
      userApi.listPage(this.pageCondition).then(res => {
        this.tableData = res.data.content
        this.pageCondition.total = parseInt(res.data.totalElements)
      })
    },
    /**
     * 处理服务器端排序
     */
    handleSortChange({ column, prop, order }) {
      // eslint-disable-next-line eqeqeq
      if (order == 'descending') {
        this.pageCondition.sort = prop ? prop + ' desc' : 'status' + ' desc'
      } else {
        this.pageCondition.sort = prop ? prop + ' asc' : 'status' + ' asc'
      }
      this.listPage()
    },
    // 获取所有的角色
    getRolesList: function() {
      roleApi.listPage().then(res => {
        this.roleOptions = res.data.content.map(item => {
          return { value: item.id, label: item.roleName }
        })
      })
    },
    // 每页显示数量调整
    handleSizeChange(val) {
      this.pageCondition.size = val
      this.listPage()
    },
    // 页面修改
    handleCurrentChange(val) {
      this.pageCondition.page = val
      this.listPage()
    },
    // 新增按钮---编辑
    handleAdd: function(row) {
      if (row) {
        this.userForm = { ...row }
        this.userForm.roles = row.roles.map(role => role.id)
        this.handleType = '编辑'
      } else {
        this.userForm = {}
        this.handleType = '新增'
      }
      this.addDialogShow = true
    },
    // 新增或修改弹窗内事件
    // 关闭弹窗前执行的事件
    handleClose: function() {
      this.addDialogShow = false
      this.checkDialogShow = false
      this.userForm = {}
    },
    // 点击确认新增或修改
    onSubmit: function(fromName) {
      const $this = this
      $this.$refs[fromName].validate(valid => {
        const data = { ...$this.userForm }
        data.roleIds = $this.userForm.roles
        delete data.roles
        if (valid) {
          if ($this.handleType === '新增') {
            userApi.add(data).then(res => {
              if (res.code === 200 && res.msg === 'ok') {
                $this.handleClose()
                $this.$notify({
                  title: '新增成功',
                  message: '该用户已成功录入系统',
                  type: 'success'
                })
                $this.listPage()
              } else {
                $this.$notify.error({
                  title: '新增失败',
                  message: '该用户未成功录入系统，请重试'
                })
              }
            })
          } else {
            userApi.edit(data).then(res => {
              if (res.code === 200 && res.msg === 'ok') {
                $this.handleClose()
                $this.$notify({
                  title: '修改成功',
                  message: '该用户修改的信息已成功录入系统',
                  type: 'success'
                })
                $this.listPage()
              } else {
                $this.$notify.error({
                  title: '修改失败',
                  message: '未成功修改锁所提交的信息，请重试'
                })
              }
            })
          }
        } else {
          return false
        }
      })
    },
    // 多选框事件
    handleSelectList: function(selection, row) {
      this.selectList = selection.map(item => item.id)
    },
    // 删除
    handleDel: function(ids) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userApi.deleteByIds({ ids }).then(res => {
          if (res.code === 200 && res.msg === 'ok') {
            this.$notify({
              title: '删除成功',
              type: 'success'
            })
            this.listPage()
          } else {
            this.$notify.error({
              title: '删除失败'
            })
          }
        })
      })
    },
    // 重置密码
    resetPassWord(userId) {
      this.$confirm('此操作将重置该用户的登陆密码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userApi.resetPwd({ userId }).then(res => {
          // eslint-disable-next-line eqeqeq
          if (res.code == 200 && res.msg == 'ok') {
            this.$message({
              type: 'success',
              message: '重置密码成功!'
            })
          }
        })
      })
    }
  }
}
</script>
<style lang="scss">
</style>
<style lang="scss" scoped>
.app-container {
  .systemuser {
    background: #fff;
    height: 100%;
    overflow: hidden;
    .btn {
      width: 100%;
      padding: 0 0 16px 0;
      display: flex;
      justify-content: space-between;
      .right{
        max-width: calc(100% - 120px);
        display: flex;
        justify-content: flex-end;
        .el-cascader{
          width: 100%;
        }
      }
    }
    .tablebox {
      overflow: auto;
      margin-bottom: 16px;
    }
    .el-select {
      width: 100%;
    }
  }
}
</style>
